from django.http import JsonResponse
from django.shortcuts import render

from main.models import Author, Book, Quote


def get_information_about_authors(request, action):
    """ Получаем информацию об авторах """

    def get_list_of_authors(request):
        list_of_authorsORM = Author.objects.values_list('name', 'slug')
        return JsonResponse({number: author for number, author in enumerate(list_of_authorsORM, 0)})

        
    # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    if 'list_of_authors' == action:
        return get_list_of_authors(request)


def get_information_about_author(request, name_slug):
    """ Получаем информацию об авторе """

    def get_list_of_books(name_slug):
        list_of_booksORM = Book.objects.filter(author__slug=name_slug).values_list('image', 'slug').all()
        list_of_books = {item: book for item, book in enumerate(list_of_booksORM)}

        return JsonResponse(list_of_books)


    def get_description_of_author(name_slug):
        description_of_author = Author.objects.get(slug=name_slug).description
        data = {'description_of_author': description_of_author}
        return JsonResponse(data)

    def get_quotes_from_authors_book(name_slug):
        data = {}
        list_of_quotes = Quote.objects.filter(book__author__slug=name_slug)

        for number, quote in enumerate(list_of_quotes):
            data[number] = {'content': quote.content,
                            'title_of_book': quote.book.title,
                            'slug_of_book': quote.book.slug,
                            'page_number': quote.page_number}

        return JsonResponse(data)


    # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    if 'list_of_books' in request.GET:
        return get_list_of_books(name_slug)

    if 'description_author' in request.GET:
        return get_description_of_author(name_slug)

    if 'quotes_from_authors_book' in request.GET:
        return get_quotes_from_authors_book(name_slug)

    author = Author.objects.get(slug=name_slug)
    context = {'author': author}
    return render(request, 'author/author.html', context)
